import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import javax.swing.tree.TreeNode;

/*
 * @lc app=leetcode.cn id=515 lang=java
 *
 * [515] 在每个树行中找最大值
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {


    public List<Integer> largestValues(TreeNode root) {

        List<Integer> res = new ArrayList<>();

        if (root == null)
            return res;

        help(root, res);
        return res;
    }

    void help(TreeNode root, List<Integer> res) {

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int maxValue = Integer.MIN_VALUE;
            for (int i = 0, len = queue.size(); i < len; i++) {
                TreeNode node = queue.poll();
                maxValue = node.val > maxValue? node.val:maxValue;
                if (node.left != null)
                    queue.offer(node.left);
                if(node.right != null)
                    queue.offer(node.right);
            }
            res.add(maxValue);
        }
    }

}
// @lc code=end

